﻿using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace YueRu.Common.Encrypt
{
    /// <summary>
    /// MD5加密操作
    /// </summary>
    public sealed class YueRuMd5
    {
        /// <summary>
        ///易车Mall签名字符串
        /// </summary>
        /// <param name="prestr">需要签名的字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>MD5结果</returns>
        [Obsolete("这个方法不要再用,因为它在MD5的时候,加入了一些逻辑,但Md5应该只做加密的事儿,请使用Md5方法")]
        public static string Sign(string prestr, string key)
        {
            var sb = new StringBuilder(32);

            prestr = prestr + key;

            MD5 md5 = new MD5CryptoServiceProvider();
            var t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(prestr.ToUpper()));
            foreach (var t1 in t)
            {
                sb.Append(t1.ToString("x").PadLeft(2, '0'));
            }

            return sb.ToString();
        }

        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="prestr">需要签名的字符串</param>
        /// <param name="sign">签名结果</param>
        /// <param name="key">密钥</param>
        /// <returns>验证结果</returns>
        public static bool Verify(string prestr, string sign, string key)
        {
            string mysign = Sign(prestr, key);
            return mysign == sign;
        }

        public static string Md5(string str)
        {
            var sb = new StringBuilder(32);
            MD5 md5 = new MD5CryptoServiceProvider();
            var t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(str));
            foreach (var t1 in t)
            {
                sb.Append(t1.ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
    }
}
